<template>
  <el-container class="custom-container-style">
    <div class="custom-adhibition-header">
      <div class="adhibition-header-l"></div>
      <div class="adhibition-header-m">
         <h1>网格化综合应用平台</h1>
         <div class="custom-adhibition-menu-style">
          <ul>
            <li v-for="(item, index) in menus" :key="index" @click="getItem(item, index)">{{item.name}}</li>
            <span class="nav_active" :style="{left:activePos}"></span>
          </ul>
        </div>
        <a class="backHome" title="返回首页" @click="handleClickBack" href="javascript:;"><em class="iconfont el-icon-extend-shouye" style="font-size: 32px;color: #1ab2ca"></em></a>
      </div>
      <div class="adhibition-header-r"></div>
    </div>
    <div id="shizhanContainer"></div>
    <div id="panel" class="scrollbar1" v-if="panelShow">
      <div class="panelWrapper">
        <el-collapse v-model="activeName" accordion id="myList">
          <el-collapse-item v-for='(item, index) in dom' :title="item.name" :name="index" :key="index" >
            <template v-if='item.items&&item.items.length>0'>
              <div class="myListItem poibox" :class='selectId===marker.id?"selected":""' v-for="(marker, i) in item.items" :key="i" @click="handleClickMaker(marker.id, marker)">
                <div class="poi-info-left">
                  <h3 class="poi-title"><span v-if='marker.communityName'>{{marker.communityName}}-</span><span v-if='marker.buildingName'>{{marker.buildingName}}-</span><span>{{marker.name}}</span></h3>
                  <div class="clear"></div>
                </div>
              </div>
            </template>
            <template v-else>
              <div  class="myListItem poibox">
                <div class="poi-info-left">
                  <h3 class="poi-title">暂无数据</h3>
                  <div class="clear"></div>
                </div>
              </div>
            </template>
          </el-collapse-item>
        </el-collapse>
      </div>

    </div>
    <el-dialog :visible.sync="dialogAppFormVisible" :title="dialogAppFormTitle" :before-close="cancel" :close-on-click-modal="false">
      <app-form :formInfo="formInfo"></app-form>
    </el-dialog>
    <div class="custom-mapInfo-style">
      <router-view @transmit="setData" :detailForm='detailForm' ref="childComponent"/>
    </div>
  </el-container>
</template>

<script>
import AppForm from '@/components/AppForm'
import {getMapLocationDown} from '@/http/AppApi'
import {getDetailHouseholdPopulation} from '@/http/PopulationApi'
import {getUserPermissionTree, getActiveModuleId, getUserGridTree} from '@/utils/SessionDataUtil'
export default {
  data () {
    return {
      dialogAppFormVisible: false,
      panelShow: false,
      formInfo: null,
      AMapUI: null,
      layer: null,
      AMap: null,
      map: null,
      dom: [],
      ids: [],
      menus: [],
      mapInfo: [],
      elements: [],
      menuList: [],
      markerList: null,
      layerHeights: [],
      currentGridIds: [],
      dialogAppFormTitle: '',
      gridZoom: {
        '06': 14.1, '05': 12.13, '04': 10.4, '03': 9.5
      },
      colors: ['#ecda9a', '#efc47e', '#f3ad6a', '#f7945d'],
      activePos: 0,
      activeName: 0,
      detailForm: {},
      defaultIconStyle: 'red',
      hoverIconStyle: 'green',
      selectedIconStyle: 'purple',
      selectId: ''
    }
  },
  components: {
    AppForm
  },
  mounted () {
    this.init()
    this.getMenus()
    this.setMenuActive()
    window.onbeforeunload = e => {
      if (this.map) {
        this.map.destroy()
      }
    }
  },
  methods: {
    init () {
      this.AMap = window.AMap
      let mapConfig = {
        resizeEnable: true,
        zoom: 10.8,
        viewMode: '3D',
        pitch: 40,
        cityName: '信阳市',
        center: [114.091104, 32.148489]
      }
      this.$nextTick(() => {
        let m = this
        this.map = new AMap.Map('shizhanContainer', mapConfig)
        this.map.setMapStyle('amap://styles/blue')
        m.map.on('mapload', function () {
          m.map.getMap().plugin(['AMap.ControlBar'], function () {
            let controlBar = new AMap.ControlBar()
            m.map.getMap().addControl(controlBar)
          })
        })
        this.map.on('complete', this.loadAreaPolygon)
      })
    },
    setData (data) {
      this.AMapUI = window.AMapUI
      this.dom = data
      this.mapInfo = data
      this.panelShow = this.mapInfo && this.mapInfo.length > 0
      if (this.markerList) {
        this.markerList.clearData()
      }
      let tempArr = []
      for (let i = 0; i < data.length; i++) {
        const element = data[i]
        for (let j = 0; j < element.items.length; j++) {
          const elementItems = element.items[j]
          tempArr.push(elementItems)
        }
        this.loadMarkerList(tempArr)
      }
      let position = new AMap.LngLat(114.091104, 32.148489)
      this.map.setCenter(position)
      this.selectId = ''
    },
    loadMarkerList (element) {
      if (this.markerList) {
        this.markerList.render(element)
        return
      }
      let m = this
      this.AMapUI.loadUI(['misc/MarkerList', 'overlay/SimpleMarker', 'overlay/SimpleInfoWindow'], function (MarkerList, SimpleMarker, SimpleInfoWindow) {
        m.markerList = new MarkerList({
          map: m.map,
          listContainer: 'myList',
          getPosition: function (item) {
            if (item.longitude && item.latitude) {
              return [item.longitude, item.latitude]
            } else {
              return [0, 0]
            }
          },
          // 数据ID，如果不提供，默认使用数组索引，即index
          getDataId: function (item, index) {
            return item.id
          },
          getInfoWindow: function (data, context, recycledInfoWindow) {
            // if (recycledInfoWindow) {
            //   recycledInfoWindow.setInfoTitle(data.name)
            //   recycledInfoWindow.setInfoBody(data.address)

            //   return recycledInfoWindow
            // }
            return new SimpleInfoWindow({
              infoTitle: data.name,
              infoBody: data.address,
              offset: new AMap.Pixel(0, -37)
            })
          },
          // 构造marker用的options对象, content和title支持模板，也可以是函数，返回marker实例，或者返回options对象
          getMarker: function (data, context, recycledMarker) {
            var label = context.index + 1
            // console.log(recycledMarker)
            // if (recycledMarker) {
            //   recycledMarker.setIconLabel(label)
            //   return
            // }
            return new SimpleMarker({
              containerClassNames: 'my-marker',
              iconStyle: m.defaultIconStyle,
              iconLabel: label,
              id: data.id,
              longitude: data.longitude,
              latitude: data.latitude
            })
          },
          // 构造列表元素，与getMarker类似，可以是函数，返回一个dom元素，或者模板 html string
          getListElement: function (data, context, recycledListElement) {
            return ''
          },
          // 列表节点上监听的事件
          listElementEvents: ['click', 'mouseenter', 'mouseleave'],
          // marker上监听的事件
          markerEvents: ['click', 'mouseover', 'mouseout'],
          makeSelectedEvents: false,
          selectedClassNames: 'selected',
          autoSetFitView: false
        })
        window.markerList = m.markerList
        m.markerList.on('markerClick', function (event, record) {
          let allMarker = m.markerList.getAllMarkers()
          for (let i = 0; i < allMarker.length; i++) {
            const element = allMarker[i]
            if (element) {
              element.setIconStyle(m.defaultIconStyle)
            }
          }
          if (record && record.marker) {
            let position = new AMap.LngLat(record.position.lng, record.position.lat)
            m.map.setCenter(position)
            record.marker.setIconStyle(m.selectedIconStyle)
            record.marker.setTop(true)
            m.detailForm = record.data
            m.$refs.childComponent.dialogShow(record.data)
          } else {
            m.$message({
              type: 'info',
              message: '没有经纬度数据'
            })
          }
        })
        m.markerList.on('listElementMouseenter markerMouseover', function (event, record) {
          if (record && record.marker) {}
        })
        m.markerList.on('listElementMouseleave markerMouseout', function (event, record) {
          if (record && record.marker) {}
        })
        m.markerList.render(element)
      })
    },
    showInfoFn (info) {
      let data = info.data
      let label = data.formName
      this.dialogAppFormTitle = data.name
      let m = this
      const request = {
        '户籍人口': () => {
          getDetailHouseholdPopulation(data.id).then(resp => {
            if (resp.code && resp.code === '200') {
              m.dialogAppFormVisible = true
              console.log(121)
            }
          })
        }
      }
      request[label]()
    },
    setMenuActive () {
      let index = sessionStorage.getItem('currentApplicationKey')
      if (index) {
        this.activePos = index * 246 + 'px'
      } else {
        this.activePos = 0
      }
    },
    loadAreaPolygon () {
      let tree = getUserGridTree()
      this.currentGridIds = []
      let m = this
      if (tree && tree instanceof Array) {
        m.treeData = tree
        if (tree.length > 0) {
          for (const key in tree) {
            if (tree.hasOwnProperty(key)) {
              let level = tree[key].levelCode
              m.map.setZoom(m.gridZoom[level])
              m.currentGridIds.push(tree[key].id)
              m.loadMapFun(tree[key].id)
            }
          }
        }
      }
    },
    loadMapFun (id) {
      let m = this
      this.loadGridMap(id).then(function (data) {
        let arr = []
        for (const j in data) {
          if (data.hasOwnProperty(j)) {
            data[j].mapArea = JSON.parse(data[j].mapArea)
            if (data[j].targetId !== id) {
              arr.push(data[j])
            }
          }
        }
        let Loca = window.Loca
        m.layer = new Loca.PolygonLayer({
          map: m.map
        })
        m.layer.setData(arr, {
          lnglat: 'mapArea'
        })
        let idx = 0
        m.layer.setOptions({
          style: {
            height: function () {
              let randomHeight = Math.random() * 20000
              m.layerHeights.push(randomHeight)
              return randomHeight
            },
            opacity: 0.9,
            color: function () {
              return m.colors[idx++ % m.colors.length]
            }
          }
        })
        m.layer.render()
        m.map.panBy(0, 204)
      }).catch(function (reason, data) {
      })
    },
    loadGridMap (id) {
      var promise = new Promise(function (resolve, reject) {
        getMapLocationDown(id).then(resp => {
          if (resp.code && resp.code === '200') {
            resolve(resp.data)
          } else {
            reject(resp.message)
          }
        })
      })
      return promise
    },
    getMenus () {
      let activeModule = getActiveModuleId()
      if (!activeModule) {
        this.$router.push({ path: '/' })
      } else {
        let permissionInfo = getUserPermissionTree()
        let currentMenuData = {}
        for (let i = 0; i < permissionInfo.length; i++) {
          if (activeModule === permissionInfo[i].id) {
            currentMenuData = permissionInfo[i]
          }
        }
        if (currentMenuData.length === 0) this.$router.push({ path: '/' })
        this.buildMenus(currentMenuData)
      }
    },
    buildMenus (menus) {
      if (menus && menus.name !== '系统设置' && menus.children) {
        this.menus = menus.children
      } else {
        this.menus = [menus]
      }
      this.menuList = this.menus[0].children
    },
    clearMarkerListData () {
      if (!this.panelShow && this.markerList) {
        this.markerList.clearData()
        this.markerList = null
      }
    },
    getItem (item, index) {
      if (window.localStorage.getItem('currentComponentId') !== item.id) {
        this.panelShow = false
      }
      this.clearMarkerListData()
      window.localStorage.setItem('currentComponentId', item.id)
      sessionStorage.setItem('currentApplicationKey', index)
      this.$router.push({path: item.uri})
      this.activePos = index * 246 + 'px'
    },
    handleClickBack () {
      sessionStorage.removeItem('currentApplicationKey')
      this.$router.push('/')
    },
    cancel () {
      this.dialogAppFormVisible = false
    },
    handleClickMaker (id, data) {
      let markerData = this.markerList.getAllMarkers()
      for (let i = 0; i < markerData.length; i++) {
        const element = markerData[i]
        element.setIconStyle(this.defaultIconStyle)
        if (element.opts.id === id) {
          if (element.opts.longitude && element.opts.latitude) {
            let position = new AMap.LngLat(element.opts.longitude, element.opts.latitude)
            this.map.setCenter(position)
          } else {
            let position = new AMap.LngLat(114.091104, 32.148489)
            this.map.setCenter(position)
            this.confirmFunc(id, data)
          }
          element.setTop(true)
          element.setIconStyle(this.selectedIconStyle)
          this.selectId = id
        }
      }
    },
    confirmFunc (id, data) {
      this.$confirm('选中信息暂无坐标，需要查看完整信息吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'customSpicia'
      }).then(() => {
        this.detailForm = data
        this.$refs.childComponent.dialogShow(data)
      }).catch(() => {

      })
    }
  }
}
</script>

<style>
#shizhanContainer{
  width: 100%;
  /* height: 100%; */
  z-index: 1;
}
.custom-mapInfo-style{
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  overflow-x: hidden;
}
.custom-adhibition-header{
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  width: 100%;
  height: 129px;
  z-index: 1000;
}
.adhibition-header-l, .adhibition-header-r {
  height: 52px;
  line-height: 52px;
  flex: 1;
  background: url('../assets/application/nav_bj_01.png') repeat-x center center;
}
.adhibition-header-m {
  position: relative;
  flex:0 0 100%;
  width: 100%;
  padding-top: 46px;
  max-width: 1920px;
  background: url('../assets/application/nav_bj.png') no-repeat center center;
}
.adhibition-header-m h1{
  text-align: center;
  padding: 0;
  height: 52px;
  line-height: 52px;
  margin: 0 auto;
  color: white;
}
.custom-adhibition-menu-style{
  width: 1215px;
  margin: 0 auto;
  height: 26px;
  line-height: 26px
}
.custom-adhibition-menu-style ul{
  position: relative;
  display: flex;
  justify-content: space-around;
  color: white;
  font-size: 14px;

}
.custom-adhibition-menu-style ul li{
  flex: 1;
  line-height: 26px;
  cursor: pointer;
  text-align: center
}
.nav_active {
  position: absolute;
  width: 235px;
  height: 6px;
  bottom: -1px;
  left: 0;
  transition: all .3s;
  background: url('../assets/application/nav_active.png') no-repeat center center;
}
#panel{
  position: absolute;
  top: 140px;
  left: 20px;
  z-index: 2;
  width:250px;
  padding: 1px;
  padding-bottom: 10px;
  max-height: 380px;
  background: url('../assets/application/panelLayer.png') no-repeat center center;
  cursor: default;
  border: 1px solid #1ab2ca;
  border-radius: 4px;
}
.panelWrapper {
  max-height: 370px;
  overflow-y: scroll;
}
.panelWrapper::-webkit-scrollbar{
  display: none
}
#panel div{
  color: white;
}
#btnList{
  right: 0;
}
.poi-title{
  padding: 0;
  margin: 0;
}
.poi-info-left{
  padding: 8px 6px;
}
.poi-info{
  padding-top: 4px;
  font-size: 14px;
}
.backHome {
  position: absolute;
  right: 20px;
  top: 45px;
  width: 100px;
  height: 35px;
  line-height: 35px;
  text-align: center;
  font-size: 16px;
  color: #fff;
  text-decoration:none
}
#myList {
  border: none
}
#myList .el-collapse-item .el-collapse-item__header, #myList .el-collapse-item .el-collapse-item__wrap {
  background: none;
  border-radius: 0;
  border-bottom: 1px solid rgba(17,192,255, 1);
}
#myList .el-collapse-item .el-collapse-item__header {
  border-bottom: 1px solid rgba(17,192,255, 1);
  padding-left: 10px;
  font-size: 16px;
}
#myList .el-collapse-item:last-child .el-collapse-item__header {
  border: none
}
#myList .el-collapse-item .el-collapse-item__header.is-active {
  border-bottom: 1px solid rgba(17,192,255, 0.8);
  border-bottom-color:rgba(17,192,255, 0.5);
}
#myList .el-collapse-item__content {
 padding-bottom: 10px
}
.poibox {
  width: 94%;
  padding: 0 5px;
  margin: 0px auto;
  border-bottom: 1px solid rgba(128,221,238,0.1);
  cursor: pointer;
}
.poibox:last-child {
  border:none
}
.poibox.selected {
 background:rgba(0, 0, 0, 0.5);
 color: #80ddee!important
}
.poibox.selected div {
 color: #11c0ff!important
}
.el-dialog {
  margin: 0 auto 10px;
}
.customSpicia {
   background: rgba(3, 52, 71, 0.8);;
   border: 1px solid rgba(121,211,238,0.8);
 }
 .customSpicia .el-message-box__content {
   color: #fff
 }
  .customSpicia .el-message-box__title {
   color: #fff
 }
</style>
